// 2013-8-31下午02:03:52  net.betou.trade.front.action.UploadAct.java

package net.betou.trade.front.action;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.betou.common.upload.FileRepository;
import net.betou.common.web.Constants;
import net.betou.common.web.ResponseUtils;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 上传Act
 * @author 叶装装
 */
@Controller
public class UploadAct{
	
	/**
	 * 统一上传接口, 该方法不参与任何的判断
	 * @param file
	 * @param request
	 * @param response
	 * @param model
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@RequestMapping( value = "/all_upload.jhtml", method = RequestMethod.POST )
	public void o_upload( String directory, @RequestParam( value = "Filedata", required = false ) MultipartFile file, HttpServletRequest request, HttpServletResponse response, ModelMap model ) throws IllegalStateException, IOException {
		responseInit( response );
		
		if( StringUtils.isBlank( directory )){
			directory = Constants.UPLOAD_DIRECTORY;
		}
		
		MultipartHttpServletRequest multipartRequest = ( MultipartHttpServletRequest ) request;

		MultipartFile uplFile = multipartRequest.getFileMap( ).entrySet( ).iterator( ).next( ).getValue( );

		String filename = FilenameUtils.getName( uplFile.getOriginalFilename( ) );

		String ext = FilenameUtils.getExtension( filename );
		
		String fileUrl = fileRepository.storeByExt( directory, ext, uplFile );
		ResponseUtils.render( response,  fileUrl );
		return;
	}

	private void responseInit( HttpServletResponse response ) {
		response.setCharacterEncoding( "UTF-8" );
		response.setContentType( "text/html" );
		response.setHeader( "Cache-Control", "no-cache" );
	}
	
	@Autowired
	private FileRepository fileRepository;
	
}
